#include<vector>
#include<unordered_map>
using namespace std;

class Solution {
public:
    int numSubarraysWithSum(vector<int>& A, int S) {
        unordered_map<int,int> map;

        int count = 0, res = 0;
        for (int i = 0; i < A.size(); ++i) {
            count += A[i];
            if (map.find(count - S) != map.end())
                res += map[count - S];
            if (map.find(count) == map.end())
                map[count] = 0;
            map[count] += 1;
            if (count == S)
                ++res;
        }
        return res;
    }
};